package org.jeecgframework.web.tcdev.controller;

import org.jboss.logging.Logger;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.tcdev.entity.TIntelligentReply;
import org.jeecgframework.web.tcdev.service.IntelligentReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 智能回复管理
 * Created by zjy on 2015/12/29.
 */
@Controller
@RequestMapping("/intelligentReplyController")
public class IntelligentReplyController {

    private static final Logger logger = Logger.getLogger(IntelligentReplyController.class);

    @Autowired
    private IntelligentReplyService intelligentReplyService;

    @Autowired
    private SystemService systemService;

    private String message;


    /**
     * 智能回复管理列表页
     * @return
     */
    @RequestMapping(params = "intelligentReplyList")
    public ModelAndView intelligentReplyList(){
        return new ModelAndView("tcdev/intelligentReply/intelligentReplyList");
    }


    /**
     * 智能回复管理列表
     * @param intelligentReply
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(TIntelligentReply intelligentReply,HttpServletRequest request,HttpServletResponse response,DataGrid dataGrid){


        CriteriaQuery cq = new CriteriaQuery(TIntelligentReply.class,dataGrid);

//        cq.eq("deleted",0);

        cq.add();
        // 查询条件组装
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, intelligentReply, request.getParameterMap());
        this.intelligentReplyService.getDataGridReturn(cq,true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 跳转到修改转视图
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(TIntelligentReply intelligentReply,
                                    HttpServletRequest req) {


        if (intelligentReply.getId() != null) {
            intelligentReply = intelligentReplyService.getEntity(TIntelligentReply.class, intelligentReply.getId());

            req.setAttribute("intelligentReply", intelligentReply);

        }


        return new ModelAndView("tcdev/intelligentReply/intelligentReply");
    }

    /**
     * 检查关键字是否重复
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "checkKeyword")
    @ResponseBody
    public ValidForm checkName(HttpServletRequest request) {
        ValidForm v = new ValidForm();
        String keyword= oConvertUtils.getString(request.getParameter("param"));
        String keyword2=oConvertUtils.getString(request.getParameter("keyword"));

        StringBuilder hql = new StringBuilder("FROM ").append(TIntelligentReply.class.getName()).append(" AS entity WHERE 1=1 ");
        hql.append(" AND entity.keyword = '").append(keyword).append("'");

        List<Object> entity = this.intelligentReplyService.findByQueryString(hql.toString());
        if(entity.size()>0 && !keyword2.equals(keyword))
        {
            v.setInfo("该关键字已存在");
            v.setStatus("n");
        }
        return v;
    }


    /**
     * 添加智能回复管理
     *
     * @param intelligentReply
     * @return
     */
    @RequestMapping(params = "save")
    @ResponseBody
    public AjaxJson save(TIntelligentReply intelligentReply, HttpServletRequest request) {

        AjaxJson j = new AjaxJson();
        if (intelligentReply.getId() != null) {

            try {

                TIntelligentReply c = intelligentReplyService.get(TIntelligentReply.class, intelligentReply.getId());

                MyBeanUtils.copyBeanNotNull2Bean(intelligentReply, c);

                intelligentReplyService.saveOrUpdate(c);

                message = MutiLangUtil.paramUpdSuccess("关键字["+intelligentReply.getKeyword()+"]");

            } catch (Exception e) {
                e.printStackTrace();
                message = MutiLangUtil.paramUpdFail("关键字["+intelligentReply.getKeyword()+"]");
            }
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } else {

            try {

                TSUser user = ResourceUtil.getSessionUserName();

                intelligentReply.setCreateTime(new Date());//创建时间
                intelligentReply.setCreater(user);//创建人

                intelligentReplyService.save(intelligentReply);

                message = MutiLangUtil.paramAddSuccess("关键字["+intelligentReply.getKeyword()+"]");
            } catch (Exception e) {
                e.printStackTrace();

                message = "保存关键字["+intelligentReply.getKeyword()+"]失败";
            }

            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除智能回复管理（物理删除）
     * @param id
     * @return
     */
    @RequestMapping(params = "del")
    @ResponseBody
    public AjaxJson del(String id){
        AjaxJson j = new AjaxJson();
        try {

            TIntelligentReply intelligentReply = intelligentReplyService.get(TIntelligentReply.class,Long.valueOf(id));

            if(intelligentReply != null){

                this.intelligentReplyService.delete(intelligentReply);

                message = "删除关键字《"+intelligentReply.getKeyword()+"》成功";
            }else{
                message = "关键字信息不存在，请刷新重试！";
            }


        } catch (Exception e) {

            message = "删除关键字失败";
        }

        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

        j.setMsg(message);
        return j;
    }

}
